package steed.netty.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.socket.SocketChannel;
import steed.netty.module.LoginMsg;
import steed.util.base.BaseUtil;
import steed.util.base.StringUtil;

public class NettyChannelMap {
    private static Map<String,Channel> clientIdChannelMap = new ConcurrentHashMap<String, Channel>();
    private static Map<ChannelId,LoginMsg> channelIdMap = new ConcurrentHashMap<ChannelId,LoginMsg>();
    
    private static Map<String, List<Channel>> userChnnelMap = new HashMap<>();
    
    public static Channel findOneChannelByUserName(String userName){
    	List<Channel> findChannelByUserName = findChannelByUserName(userName);
    	if (findChannelByUserName.isEmpty()) {
			return null;
		}
    	return findChannelByUserName.get(0);
    }
    
    public static List<Channel> findChannelByUserName(String userName){
    	List<Channel> list = userChnnelMap.get(userName);
    	if (list == null) {
			list = new ArrayList<>();
			userChnnelMap.put(userName, list);
		}
		return list;
    }
    public static void onLogin(LoginMsg msg,Channel channel){
    	if (msg.getClientId() == null) {
    		msg.setClientId(StringUtil.getSecureRandomString());
    	}
    	findChannelByUserName(msg.getUserName()).add(channel);
    	channelIdMap.put(channel.id(), msg);
    	clientIdChannelMap.put(msg.getClientId(),channel);
    }
    
    public static Channel get(String clientId){
       return clientIdChannelMap.get(clientId);
    }
    public static String getClientId(Channel channel){
    	return getClientId(channel.id());
    }
    public static String getClientId(ChannelId channelId){
    	LoginMsg loginMsg = channelIdMap.get(channelId);
    	if (loginMsg == null) {
			return null;
		}
		return loginMsg.getClientId();
    }
    public static Map<String, Channel> getMap(){
    	return clientIdChannelMap;
    }
    public static void remove(SocketChannel socketChannel){
        for (Map.Entry<String, Channel> entry:clientIdChannelMap.entrySet()){
            if (entry.getValue()==socketChannel){
            	BaseUtil.getLogger().debug("客户端{}{}", entry.getKey(),"断线");
                clientIdChannelMap.remove(entry.getKey());
                ChannelId channelId = entry.getValue().id();
				LoginMsg loginMsg = channelIdMap.get(channelId);
				List<Channel> list = userChnnelMap.get(loginMsg.getUserName());
				list.remove(socketChannel);
				if (list.isEmpty()) {
					userChnnelMap.remove(loginMsg.getUserName());
				}
                channelIdMap.remove(channelId);
            }
        }
    }

}
